<?php
defined('BY_JYA') or exit('error');
global $_RQ,$_AR;
$_RQ['op']=$_RQ['op']?$_RQ['op']:'get';
$return=array();

if($_RQ['op']=='get'){
	$return['item']=array();
	$return['htmls']=array (
		  'type' => 'edit',
		  'post' => 'post',
		  'edit_tab' => '采集商品',
		  'edits' => 
		  array (
		    0 => 
		    array (
		      'title' => '采集商品',
		      'list' => 
		      array (
				array ('name' => 'url','type' => 'string','title' => '链接 或 itemId','help'=>'例如商品链接为: https://item.taobao.com/item.htm?id=586126013807或:http://detail.tmall.com/item.htm?id=586126013807直接输入商品链接或输入商品ID:586126013807'),
		      ),
		    ),
		  ),
		);
	exi($return);
}
if($_RQ['op']=='post'){
	$postdata=get_postdata();	
	set_time_limit(0);
	$ret = array();
//	$_RQ['url']='http://item.taobao.com/item.htm?id=557143503333';
	$url = $postdata['url'];
	$cates = $postdata['cate'];
	$from = $_RQ['from'];
	$from='taobao';
		if (is_numeric($url)) {
			$itemid = $url;
		}
		else{
			preg_match('/id\\=(\\d+)/i', $url, $matches);

			if(isset($matches[1])) {
				$itemid = $matches[1];
			}
		}	
		if (empty($itemid)) {
			exi('未获取到 itemid!','error');
		}
		if ($from == 'all') {
			$ret = get_item_taobao($itemid, $_RQ['url'], $cates);
		}
		else if ($from == 'tmall') {
			$ret =get_item_tmall_bypage($itemid, $_RQ['url'], $cates);
		}
		else {
			if ($from == 'taobao') {
				$ret = get_item_taobao($itemid, $_RQ['url'], $cates);
			}
		}

		//plog('taobao.main', '淘宝抓取宝贝 淘宝id:' . $itemid);
		
		if($ret['result']==1){
			exi('采集商品成功','','jy_weishop/goods.list/edit/id='.$ret['goodsid']);
		}else{
			exi('采集失败：'.$ret['error'],'error');
		}
		
}
function get_item_taobao($itemid = '', $taobaourl = '', $cates = '', $merchid = 0) 
	{  
	
		error_reporting(0);
		$goodsid=pdo_getcolumn('jy_tbassistant_catch',array('catch_source' => 'taobao', 'catch_id' => $itemid),'goodsid');
		$g = pdo_fetch('select * from ' . tablename('jy_weishop_goods') . ' where uniacid=:uniacid and merchid=:merchid and id=:id limit 1', array(':uniacid' => $_SESSION['uniacid'], ':merchid' => $merchid, ':id' =>$goodsid));
		$item = array();
		$item['id'] = $g['id'];
		$item['merchid'] = $merchid;
		$item['itemId'] = $itemid;
		
		if (!(empty($merchid))) 
		{
			if (empty($_SESSION['merch_user']['goodschecked'])) 
			{
				$item['checked'] = 1;
			}
			else 
			{
				$item['checked'] = 0;
			}
		}
		
		$url = get_tmall_page_url($itemid);
		//load()->func('communication');
		
		$response =cfc('http')->ihttp_get($url);
		
		
		$length = strval($response['headers']['Content-Length']);
		
		if ($length != NULL) 
		{
			return array('result' => '0', 'error' => '未从淘宝获取到商品信息!');
		}
		$content = $response['content'];
		if (function_exists('mb_convert_encoding')) 
		{
			$content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
		}
		
		if (strexists($response['content'], 'ERRCODE_QUERY_DETAIL_FAIL')) 
		{ 
			return array('result' => '0', 'error' => '宝贝不存在!');
		}
		
		$dom = new DOMDocument(); 
		$dom->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' . $content);
		
		$xml = simplexml_import_dom($dom);
		//file_put_contents('tb.txt',$content);exit;
		preg_match('/var g_config\\s*=(.*);/isU', $content, $match);
		//print_r($xml);exit;
		$matchOne = str_replace(array(' ', "\r", "\n", "\t"), array(''), $match[1]);
		$erdr = substr($matchOne, stripos($matchOne, 'sibUrl')); 
		$erdr2 = substr($erdr, 0, stripos($erdr, 'descUrl'));
		$asd = explode(':', $erdr2);
		$two = substr($asd[1], 1);
		$threeUrl = substr($two, 0, -2);
		$detailskip = cfc('http')->ihttp_request('https:' . $threeUrl, '', array('referer' => 'https://item.taobao.com?id=' . $itemid, 'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'accept-encoding' => '', 'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8', 'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'CURLOPT_USERAGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'));
		$detailskip = json_decode($detailskip['content'], true);

		$stockArray = array();
		if (($detailskip['code']['code'] == 0) && ($detailskip['code']['message'] == 'SUCCESS')) 
		{
			$stockArray = $detailskip['data']['dynStock']['sku'];
		}
		$specifications = $xml->xpath('//*[@id="J_isku"]/div/dl/dd/ul');
		
		$specificationsArray = array();
		$guigeArr = array();
		foreach ($specifications as $key => $specificationsInfo ) 
		{
			$sizeArray = (array) $specificationsInfo;
			$sizeAttributesArray = explode(':', $sizeArray['@attributes']['data-property']);
			$specificationsArray[$key]['title'] = $sizeAttributesArray[0];
			$sizeLiArray = $sizeArray['li'];
			if (!(is_object($sizeLiArray))) 
			{
				$specificationsArray[$key]['itemsCount'] = count($sizeLiArray);
				foreach ($sizeLiArray as $j => $sizeLiInfo ) 
				{
					$sizeLiInfoArray = (array) $sizeLiInfo;
					$guigeArr[$key][$j][] = ';' . $sizeLiInfoArray['@attributes']['data-value'];
					$sizeLiInfoAttributesArray = explode(':', $sizeLiInfoArray['@attributes']['data-value']);
					$specificationsArray[$key]['propId'] = $sizeLiInfoAttributesArray[0];
					$specificationsArray[$key]['items'][$j]['valueId'] = $sizeLiInfoAttributesArray[1];
					$sizeLiInfoA = (array) $sizeLiInfoArray['a'];
					$specificationsTitle = (array) $sizeLiInfoA['span'];
					$specificationsArray[$key]['items'][$j]['title'] = $specificationsTitle[0];
					$guigeArr[$key][$j][] = $specificationsTitle[0];
					$sizeLiInfoAttr = $sizeLiInfoA['@attributes'];
					if (!(empty($sizeLiInfoAttr['style']))) 
					{
						$sizeLiInfoAttrStyle = substr($sizeLiInfoAttr['style'], stripos($sizeLiInfoAttr['style'], '//'));
						$sizeLiInfoAttrStyleUrl = substr($sizeLiInfoAttrStyle, 0, stripos($sizeLiInfoAttrStyle, ')'));
						$thumb = mb_substr($sizeLiInfoAttrStyleUrl, 0, strpos($sizeLiInfoAttrStyleUrl, '_30x30.jpg'));
						$specificationsArray[$key]['items'][$j]['thumb'] = 'http:' . $thumb;
					}
					else 
					{
						$specificationsArray[$key]['items'][$j]['thumb'] = '';
					}
				}
			}
			else 
			{
				$objsctArr = (array) $sizeLiArray;
				$specificationsArray[$key]['itemsCount'] = 1;
				$objsctArrAttributes = explode(':', $objsctArr['@attributes']['data-value']);
				$specificationsArray[$key]['propId'] = $objsctArrAttributes[0];
				$specificationsArray[$key]['items'][0]['valueId'] = $objsctArrAttributes[1];
				$sizeLiInfoA = (array) $objsctArr['a'];
				$specificationsTitle = (array) $sizeLiInfoA['span'];
				$specificationsArray[$key]['items'][0]['title'] = $specificationsTitle[0];
				$guigeArr[$key][0][] = ';' . $objsctArr['@attributes']['data-value'];
				$guigeArr[$key][0][] = $specificationsTitle[0];
				$sizeLiInfoAttr = $sizeLiInfoA['@attributes'];
				if (!(empty($sizeLiInfoAttr['style']))) 
				{
					$sizeLiInfoAttrStyle = substr($sizeLiInfoAttr['style'], stripos($sizeLiInfoAttr['style'], '//'));
					$sizeLiInfoAttrStyleUrl = substr($sizeLiInfoAttrStyle, 0, stripos($sizeLiInfoAttrStyle, ')'));
					$thumb = mb_substr($sizeLiInfoAttrStyleUrl, 0, strpos($sizeLiInfoAttrStyleUrl, '_30x30.jpg'));
					$specificationsArray[$key]['items'][0]['thumb'] = 'http:' . $thumb;
				}
				else 
				{
					$specificationsArray[$key]['items'][0]['thumb'] = '';
				}
			}
		}
		
		$item['specs'] = my_sort($specificationsArray, 'itemsCount', SORT_ASC, SORT_STRING);
		
		$count = count($guigeArr);
		
		if ($count == 1) 
		{
			$i = 0;
			while ($i < count($guigeArr[0])) 
			{
				$value = $guigeArr[0][$i][0];
				$title = $guigeArr[0][$i][1];
				$arr[] = $value . ';|' . $title;
				++$i;
			}
		}
		else if ($count == 2) 
		{
			$i = 0;
			while ($i < count($guigeArr[0])) 
			{
				$value = $guigeArr[0][$i][0];
				$title = $guigeArr[0][$i][1];
				$j = 0;
				while ($j < count($guigeArr[1])) 
				{
					$valueTwo = $value . $guigeArr[1][$j][0];
					$titleTwo = $title . '+' . $guigeArr[1][$j][1];
					$arr[] = $valueTwo . ';|' . $titleTwo;
					++$j;
				}
				++$i;
			}
		}
		else if ($count == 3) 
		{
			$i = 0;
			while ($i < count($guigeArr[0])) 
			{
				$value = $guigeArr[0][$i][0];
				$title = $guigeArr[0][$i][1];
				$j = 0;
				while ($j < count($guigeArr[1])) 
				{
					$valueTwo = $value . $guigeArr[1][$j][0];
					$titleTwo = $title . '+' . $guigeArr[1][$j][1];
					$g = 0;
					while ($g < count($guigeArr[2])) 
					{
						$valueThree = $valueTwo . $guigeArr[2][$g][0];
						$titleThree = $titleTwo . '+' . $guigeArr[2][$g][1];
						$arr[] = $valueThree . ';|' . $titleThree;
						++$g;
					}
					++$j;
				}
				++$i;
			}
		}
		else if ($count == 4) 
		{
			$i = 0;
			while ($i < count($guigeArr[0])) 
			{
				$value = $guigeArr[0][$i][0];
				$title = $guigeArr[0][$i][1];
				$j = 0;
				while ($j < count($guigeArr[1])) 
				{
					$valueTwo = $value . $guigeArr[1][$j][0];
					$titleTwo = $title . '+' . $guigeArr[1][$j][1];
					$g = 0;
					while ($g < count($guigeArr[2])) 
					{ 
						$valueThree = $valueTwo . $guigeArr[2][$g][0];
						$titleThree = $titleTwo . '+' . $guigeArr[2][$g][1];
						$r = 0;
						while ($r < count($guigeArr[3])) 
						{
							$valueFour = $valueThree . $guigeArr[3][$r][0];
							$titleFour = $titleThree . '+' . $guigeArr[3][$r][1];
							$arr[] = $valueFour . ';|' . $titleFour;
							++$r;
						}
						++$g;
					}
					++$j;
				}
				++$i;
			}
		}
		else if ($count == 5) 
		{
			$i = 0;
			while ($i < count($guigeArr[0])) 
			{
				$value = $guigeArr[0][$i][0];
				$title = $guigeArr[0][$i][1];
				$j = 0;
				while ($j < count($guigeArr[1])) 
				{
					$valueTwo = $value . $guigeArr[1][$j][0];
					$titleTwo = $title . '+' . $guigeArr[1][$j][1];
					$g = 0;
					while ($g < count($guigeArr[2])) 
					{ 
						$valueThree = $valueTwo . $guigeArr[2][$g][0];
						$titleThree = $titleTwo . '+' . $guigeArr[2][$g][1];
						$r = 0;
						while ($r < count($guigeArr[3])) 
						{ 
							$valueFour = $valueThree . $guigeArr[3][$g][0];
							$titleFour = $titleThree . '+' . $guigeArr[3][$g][1];
							$t = 0;
							while ($t < count($guigeArr[4])) 
							{
								$valueFive = $valueFour . $guigeArr[4][$t][0];
								$titleFive = $titleFour . '+' . $guigeArr[4][$t][1];
								$arr[] = $valueFive . ';|' . $titleFive;
								++$t;
							}
							++$r;
						}
						++$g;
					}
					++$j;
				}
				++$i;
			}
		}
		else if ($count == 6) 
		{
			$i = 0;
			while ($i < count($guigeArr[0])) 
			{
				$value = $guigeArr[0][$i][0];
				$title = $guigeArr[0][$i][1];
				$j = 0;
				while ($j < count($guigeArr[1])) 
				{
					$valueTwo = $value . $guigeArr[1][$j][0];
					$titleTwo = $title . '+' . $guigeArr[1][$j][1];
					$g = 0;
					while ($g < count($guigeArr[2])) 
					{
						$valueThree = $valueTwo . $guigeArr[2][$g][0];
						$titleThree = $titleTwo . '+' . $guigeArr[2][$g][1];
						$r = 0;
						while ($r < count($guigeArr[3])) 
						{
							$valueFour = $valueThree . $guigeArr[3][$g][0];
							$titleFour = $titleThree . '+' . $guigeArr[3][$g][1];
							$t = 0;
							while ($t < count($guigeArr[4])) 
							{
								$valueFive = $valueFour . $guigeArr[4][$t][0];
								$titleFive = $titleFour . '+' . $guigeArr[4][$t][1];
								$k = 0;
								while ($k < count($guigeArr[5])) 
								{
									$valueSix = $valueFive . $guigeArr[5][$k][0];
									$titleSix = $titleFive . '+' . $guigeArr[5][$k][1];
									$arr[] = $valueSix . ';|' . $titleSix;
									++$k;
								}
								++$t;
							}
							++$r;
						}
						++$g;
					}
					++$j;
				}
				++$i;
			}
		}
		$item['options'] = array();
		$item['total'] = 0;
		foreach ($arr as $key => $asdInfo ) 
		{
			$asdInfoArrAs = explode('|', $asdInfo);
			$asdInfoArr = explode(';', $asdInfoArrAs[0]);
			$asdInfoArr = array_filter($asdInfoArr);
			$j = 0;
			foreach ($asdInfoArr as $asdInfoArrInfo ) 
			{
				$asdInfoArrInfoArr = explode(':', $asdInfoArrInfo);
				$item['options'][$key]['option_specs'][$j]['propId'] = $asdInfoArrInfoArr[0];
				$item['options'][$key]['option_specs'][$j]['valueId'] = $asdInfoArrInfoArr[1];
				++$j;
			}
			if (!(empty($stockArray[$asdInfoArrAs[0]]))) 
			{
				$item['options'][$key]['stock'] = $stockArray[$asdInfoArrAs[0]]['stock'];
				$item['total'] = $item['total'] + $stockArray[$asdInfoArrAs[0]]['stock'];
			}
			else 
			{
				$item['options'][$key]['stock'] = 0;
			}
			$item['options'][$key]['title'] = explode('+', $asdInfoArrAs[1]);
			$item['options'][$key]['marketprice'] = $detailskip['data']['price'];
		}
		$prodectNameContent = $xml->xpath('//*[@id="J_Title"]');
		$titleArr = (array) $prodectNameContent[0];
		$item['title'] = trim(strval($titleArr['h3']));
		//print_r($item['title']);exit;
		//$prodectNameContent = $xml->xpath('//*[@class="tb-detail-hd"]');
		//$titleArr = (array) $prodectNameContent[0];
		//$titleArr['h1']=json_encode($titleArr['h1']);
		//$titleArr['h1']=json_decode($titleArr['h1'],true);
		//$item['title'] = $titleArr['h1']['a'];
		
		$prodectDescContent = $xml->xpath('//div/div/div/div/div/div/div/div/div/div/div[1]');
		$item['subTitle'] = trim(strval($prodectDescContent[1]->p));
		$prodectPrice = $xml->xpath('//*[@id="J_StrPrice"]');
		$prodectPriceArr = (array) $prodectPrice[0];
		$taoBaoPrice = trim(strval($prodectPriceArr['em'][1]));
		$taoBaoPriceArr = explode('-', $taoBaoPrice);
		$item['productPrice'] = $taoBaoPriceArr[0];
		//$prodectPrice = $xml->xpath('//*[@class="tm-price"]');

		//print_r($item['productPrice'].'fff');exit;
		$imgs = array();
		$i = 1;
		
		while ($i < 6) 
		{  
			$img = $xml->xpath('//*[@id="J_UlThumb"]/li[' . $i . ']');
			
			if (!(empty($img))) 
			{
				$img = strval($img[0]->div->a->img['data-src']);
				$img = mb_substr($img, 0, strpos($img, '_50x50.jpg'));
				
				$imgArr = explode(':', $img);
				if (count($imgArr) == 2) 
				{
					$img = 'http:' . $imgArr[1];
				}
				else 
				{
					$img = 'http:' . $imgArr[0];
				}
				$imgs[] = $img;
			}
			++$i;
		}
		$item['pics'] = $imgs;
		$paramsContent = $xml->xpath('//*[@id="attributes"]');
		$paramsContent = $paramsContent[0]->ul->li;
		$paramsContent = (array) $paramsContent;
		if (!(empty($paramsContent['@attributes']))) 
		{
			unset($paramsContent['@attributes']);
		}
		$params = array();
		foreach ($paramsContent as $paramitem ) 
		{
			$paramitem = strval($paramitem);
			if (!(empty($paramitem))) 
			{
				$paramitem = trim(str_replace('：', ':', $paramitem));
				$p1 = mb_strpos($paramitem, ':');
				$ptitle = mb_substr($paramitem, 0, $p1);
				$pvalue = mb_substr($paramitem, $p1 + 1, mb_strlen($paramitem));
				$param = array('title' => $ptitle, 'value' => $pvalue);
				$params[] = $param;
			}
		}
		$item['params'] = $params;
		$pcates = array();
		$ccates = array();
		$tcates = array();
		$pcateid = 0;
		$ccateid = 0;
		$tcateid = 0;
		
		if (is_array($cates)) 
		{
			foreach ($cates as $key => $cid ) 
			{
				$c = pdo_fetch('select level from ' . tablename('jy_weishop_category') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $cid, ':uniacid' => $_SESSION['uniacid']));
				if ($c['level'] == 1) 
				{
					$pcates[] = $cid;
				}
				else if ($c['level'] == 2) 
				{
					$ccates[] = $cid;
				}
				else if ($c['level'] == 3) 
				{
					$tcates[] = $cid;
				}
				if ($key == 0) 
				{
					if ($c['level'] == 1) 
					{
						$pcateid = $cid;
					}
					else if ($c['level'] == 2) 
					{
						$crow = pdo_fetch('select parentid from ' . tablename('jy_weishop_category') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $cid, ':uniacid' => $_SESSION['uniacid']));
						$pcateid = $crow['parentid'];
						$ccateid = $cid;
					}
					else if ($c['level'] == 3) 
					{
						$tcateid = $cid;
						$tcate = pdo_fetch('select id,parentid from ' . tablename('jy_weishop_category') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $cid, ':uniacid' => $_SESSION['uniacid']));
						$ccateid = $tcate['parentid'];
						$ccate = pdo_fetch('select id,parentid from ' . tablename('jy_weishop_category') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $ccateid, ':uniacid' => $_SESSION['uniacid']));
						$pcateid = $ccate['parentid'];
					}
				}
			}
		}
		$item['pcate'] = $pcateid;
		$item['ccate'] = $ccateid;
		$item['tcate'] = $tcateid;
		if (!(empty($cates))) 
		{
			$item['cates'] = implode(',', $cates);
		}
		$item['pcates'] = implode(',', $pcates);
		$item['ccates'] = implode(',', $ccates);
		$item['tcates'] = implode(',', $tcates);
		
		$url = get_taobao_detail_url($itemid);
		
		//load()->func('communication');
		
		$response = cfc('http')->ihttp_get($url);
		$response =contentpasswh($response);
		$item['content'] = $response;
		//print_r($response);exit;
		return save_taobao_goods($item, $taobaourl);
	}
	
	
	
function get_tmall_page_url($itemid) {
		$url = 'https://detail.tmall.com/item.htm?id=' . $itemid;
		$url =getRealURL($url);
		return $url;
}

function getRealURL($url) {
		if (function_exists('stream_context_set_default')) 
		{
			stream_context_set_default(array( 'http' => array('method' => 'HEAD') ));
		}
		$header = get_headers($url, 1);
		if (strpos($header[0], '301') || strpos($header[0], '302')) 
		{
			if (is_array($header['Location'])) 
			{
				return $header['Location'][count($header['Location']) - 1];
			}
			return $header['Location'];
		}
		return $url;
}
function my_sort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC) {
		if (is_array($arrays)) 
		{
			foreach ($arrays as $array ) 
			{
				if (is_array($array)) 
				{
					$key_arrays[] = $array[$sort_key];
				}
				else 
				{
					return false;
				}
			}
		}
		else 
		{
			return false;
		}
		array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
		return $arrays;
}
function get_taobao_detail_url($itemid) {
		$url = 'http://hws.m.taobao.com/cache/wdesc/5.0/?id=' . $itemid;
		$url = getRealURL($url);
		return $url;
}
function contentpasswh($content) {
		$content = preg_replace('/(?:width)=(\'|").*?\\1/', ' width="100%"', $content);
		$content = preg_replace('/(?:height)=(\'|").*?\\1/', ' ', $content);
		$content = preg_replace('/(?:max-width:\\s*\\d*\\.?\\d*(px|rem|em))/', '', $content);
		$content = preg_replace('/(?:max-height:\\s*\\d*\\.?\\d*(px|rem|em))/', '', $content);
		$content = preg_replace('/(?:min-width:\\s*\\d*\\.?\\d*(px|rem|em))/', ' ', $content);
		$content = preg_replace('/(?:min-height:\\s*\\d*\\.?\\d*(px|rem|em))/', ' ', $content);
		return $content;
}
function save_taobao_goods($item = array(), $catch_url = '') 
	{   
		$params=array('uniacid'=>$_SESSION['uniacid'],'catch_source' => 'taobao', 'catch_id' => $item['itemId'], 'catch_url' => $catch_url);
		$data = array('uniacid' => $_SESSION['uniacid'],'param'=>ijson_encode($item['params']),'title' => $item['title'], 'subtitle' => $item['subTitle'], 'merchid' => $item['merchid'], 'checked' => $item['checked'],'title' => $item['title'], 'total' => $item['total'], 'marketprice' => $item['marketprice'], 'costprice' => $item['productPrice'], 'pcate' => $item['pcate'], 'ccate' => $item['ccate'], 'tcate' => $item['tcate'], 'cates' => $item['cates'], 'salenum' => $item['sales'], 'createtime' => time(), 'updatetime' => time(), 'isoption' => (0 < count($item['options']) ? 1 : 0), 'status' => 0, 'buylevels' => '', 'showlevels' => '', 'buygroups' => '', 'showgroups' => '', 'storeids' => '');
		if (empty($item['merchid'])) 
		{
			//$data['discounts'] = '{"type":"0","default":"","default_pay":""}';
		}
		$thumb_url = array();
		$pics = $item['pics'];
		$cs=cfc('http')->ihttp_get($pics[0]);
		//print_r($cs);exit;
		$piclen = count($pics);
		if (0 < $piclen) 
		{
			$img=cfc('files')->source_save($cs['content'],'image','jpg','商品单图','',0);
					
			if (empty($img)) 
				{
					$img = $pics[0];
				}
			$data['image'] = $img;
			if (1 < $piclen) 
			{
				$i = 1;
				
				while ($i < $piclen) 
				{	
					$pic=cfc('http')->ihttp_get($pics[$i]);
					$imgs=cfc('files')->source_save($pic['content'],'image','jpg','商品多图','',0);
					if (empty($imgs)) 
					{
						$imgs = $pics[$i];
					}
					$thumb_url[] = $imgs;
					++$i;
				}
				$data['images']=json_encode($thumb_url);
			}
		}
		$data['type']=0;
		$gid=pdo_getcolumn('jy_tbassistant_catch',array('catch_source' => 'taobao', 'catch_id' => $item['itemId']),'goodsid');
		$goods = pdo_get('jy_weishop_goods',array('uniacid'=>$_SESSION['uniacid'],'id'=>$gid));
		if (empty($goods)) 
		{
			//print_r('插入数据');exit;
			pdo_insert('jy_weishop_goods', $data);
			$goodsid = pdo_insertid();
			$params['goodsid']=$goodsid;
			pdo_insert('jy_tbassistant_catch', $params);

		}
		else 
		{
			$goodsid = $goods['id'];
			unset($data['createtime']);
			pdo_update('jy_weishop_goods', $data, array('id' => $goodsid));
		}
		//$goods_params = pdo_fetchall('select * from ' . tablename('jy_weishop_goods_param') . ' where goodsid=:goodsid ', array(':goodsid' => $goodsid));
		//$params = $item['params'];
		/*$paramids = array();
		$displayorder = 0;
		foreach ($params as $p ) 
		{
			$oldp = pdo_fetch('select * from ' . tablename('jy_weishop_goods_param') . ' where goodsid=:goodsid and title=:title limit 1', array(':goodsid' => $goodsid, ':title' => $p['title']));
			$paramid = 0;
			$d = array('uniacid' => $_SESSION['uniacid'], 'goodsid' => $goodsid, 'title' => $p['title'], 'value' => $p['value'], 'displayorder' => $displayorder);
			if (empty($oldp)) 
			{
				pdo_insert('jy_weishop_goods_param', $d);
				$paramid = pdo_insertid();
			}
			else 
			{
				pdo_update('jy_weishop_goods_param', $d, array('id' => $oldp['id']));
				$paramid = $oldp['id'];
			}
			$paramids[] = $paramid;
			++$displayorder;
		}
		if (0 < count($paramids)) 
		{
			pdo_query('delete from ' . tablename('jy_weishop_goods_param') . ' where goodsid=:goodsid and id not in (' . implode(',', $paramids) . ')', array(':goodsid' => $goodsid));
		}
		else 
		{
			pdo_query('delete from ' . tablename('jy_weishop_goods_param') . ' where goodsid=:goodsid ', array(':goodsid' => $goodsid));
		}
		*/
		$specs = $item['specs'];
	//	print_r($specs);exit;
		$specids = array();
		$displayorder = 0;
		$newspecs = array();
		foreach ($specs as $spec ) 
		{
			$oldspec = pdo_fetch('select * from ' . tablename('jy_weishop_goods_spec') . ' where goodsid=:goodsid and propId=:propId limit 1', array(':goodsid' => $goodsid, ':propId' => $spec['propId']));
			$specid = 0;
			$d_spec = array('uniacid' => $_SESSION['uniacid'], 'goodsid' => $goodsid, 'title' => $spec['title'], 'paixu' => $displayorder, 'propId' => $spec['propId']);
			if (empty($oldspec)) 
			{
				pdo_insert('jy_weishop_goods_spec', $d_spec);
				$specid = pdo_insertid();
			}
			else 
			{
				pdo_update('jy_weishop_goods_spec', $d_spec, array('id' => $oldspec['id']));
				$specid = $oldspec['id'];
			}
			$d_spec['id'] = $specid;
			$specids[] = $specid;
			++$displayorder;
			$spec_items = $spec['items'];
			$spec_itemids = array();
			$displayorder_item = 0;
			$newspecitems = array();
			foreach ($spec_items as $spec_item ) 
			{
				$d = array('uniacid' => $_SESSION['uniacid'], 'specid' => $specid, 'title' => $spec_item['title'], 'thumb' =>$spec_item['thumb'], 'valueId' => $spec_item['valueId'], 'show' => 1, 'paixu' => $displayorder_item);
				$oldspecitem = pdo_fetch('select * from ' . tablename('jy_weishop_goods_spec_item') . ' where specid=:specid and valueId=:valueId limit 1', array(':specid' => $specid, ':valueId' => $spec_item['valueId']));
				$spec_item_id = 0;
				if (empty($oldspecitem)) 
				{
					pdo_insert('jy_weishop_goods_spec_item', $d);
					$spec_item_id = pdo_insertid();
				}
				else 
				{
					pdo_update('jy_weishop_goods_spec_item', $d, array('id' => $oldspecitem['id']));
					$spec_item_id = $oldspecitem['id'];
				}
				++$displayorder_item;
				$spec_itemids[] = $spec_item_id;
				$d['id'] = $spec_item_id;
				$newspecitems[] = $d;
			}
			$d_spec['items'] = $newspecitems;
			$newspecs[] = $d_spec;
			if (0 < count($spec_itemids)) 
			{
				pdo_query('delete from ' . tablename('jy_weishop_goods_spec_item') . ' where specid=:specid and id not in (' . implode(',', $spec_itemids) . ')', array(':specid' => $specid));
			}
			else 
			{
				pdo_query('delete from ' . tablename('jy_weishop_goods_spec_item') . ' where specid=:specid ', array(':specid' => $specid));
			}
			pdo_update('jy_weishop_goods_spec', array('content' => serialize($spec_itemids)), array('id' => $oldspec['id']));
		}
		if (0 < count($specids)) 
		{
			pdo_query('delete from ' . tablename('jy_weishop_goods_spec') . ' where goodsid=:goodsid and id not in (' . implode(',', $specids) . ')', array(':goodsid' => $goodsid));
		}
		else 
		{
			pdo_query('delete from ' . tablename('jy_weishop_goods_spec') . ' where goodsid=:goodsid ', array(':goodsid' => $goodsid));
		}
		$minprice = 0;
		$options = $item['options'];
		if (0 < count($options)) 
		{
			$minprice = $options[0]['marketprice'];
		}
		$optionids = array();
		$displayorder = 0;
		//print_r($options);exit;
		foreach ($options as $o ) 
		{	
			$option_specs = $o['option_specs'];
			$ids = array();
			$valueIds = array();
			foreach ($option_specs as $os ) 
			{
				foreach ($newspecs as $nsp ) 
				{
					foreach ($nsp['items'] as $nspitem ) 
					{
						if ($nspitem['valueId'] == $os['valueId']) 
						{
							$ids[] = $nspitem['id'];
							$valueIds[] = $nspitem['valueId'];
						}
					}
				}
			}
			asort($ids);
			$ids = implode('_', $ids);
			$valueIds = implode('_', $valueIds);
			$do = array('uniacid' => $_SESSION['uniacid'], 'paixu' => $displayorder, 'goodsid' => $goodsid, 'title' => implode('+', $o['title']), 'specs' => $ids, 'stock' => $o['stock'], 'price' => $o['marketprice'], 'skuId' => $o['option_specs']['0']['valueId']);
			if ($o['marketprice'] < $minprice) 
			{
				$minprice = $o['marketprice'];
			}
			//$oldoption = pdo_fetch('select * from ' . tablename('jy_weishop_goods_option') . ' where goodsid=:goodsid and skuId=:skuId limit 1', array(':goodsid' => $goodsid, ':skuId' => $o['skuId']));
			$oldoption = pdo_fetch('select * from ' . tablename('jy_weishop_goods_option') . ' where goodsid=:goodsid and skuId=:skuId limit 1', array(':goodsid' => $goodsid, ':skuId' => $o['option_specs']['0']['valueId']));
			$option_id = 0;
			if (empty($oldoption)) 
			{
				pdo_insert('jy_weishop_goods_option', $do);
				$option_id = pdo_insertid();
			}
			else 
			{
				pdo_update('jy_weishop_goods_option', $do, array('id' => $oldoption['id']));
				$option_id = $oldoption['id'];
			}
			++$displayorder;
			$optionids[] = $option_id;
		}
		if (0 < count($optionids)) 
		{
			pdo_query('delete from ' . tablename('jy_weishop_goods_option') . ' where goodsid=:goodsid and id not in (' . implode(',', $optionids) . ')', array(':goodsid' => $goodsid));
		}
		else 
		{
			pdo_query('delete from ' . tablename('jy_weishop_goods_option') . ' where goodsid=:goodsid ', array(':goodsid' => $goodsid));
		}
		/*
		$response = $item['content'];
		$content = $response['content'];
		preg_match_all('/<img.*?src=[\\\\\'| \\"](.*?(?:[\\.gif|\\.jpg]?))[\\\\\'|\\"].*?[\\/]?>/', $content, $imgs);
		if (isset($imgs[1])) 
		{
			foreach ($imgs[1] as $img ) 
			{
				$catchimg = $img;
				if (substr($catchimg, 0, 2) == '//') 
				{
					$img = 'http://' . substr($img, 2);
				}
				$im = array('catchimg' => $catchimg, 'system' => $this->save_image($img, true));
				$images[] = $im;
			}
		}
		preg_match('/tfsContent : \\\'(.*)\\\'/', $content, $html);
		$html = iconv('GBK', 'UTF-8', $html[1]);
		if (isset($images)) 
		{
			foreach ($images as $img ) 
			{
				if (!(empty($img['system']))) 
				{
					$html = str_replace($img['catchimg'], $img['system'], $html);
				}
			}
		}
		$html = m('common')->html_to_images($html);
		$hasoption = 0;
		if (0 < count($options)) 
		{
			$hasoption = 1;
		}
		$d = array('content' => $html, 'hasoption' => $hasoption);
		if (0 < $minprice) 
		{
			$d['marketprice'] = $minprice;
		}
		pdo_update('jy_weishop_goods', $d, array('id' => $goodsid));
		if ($d['hasoption']) 
		{
			$sql = 'update ' . tablename('jy_weishop_goods') . ' g set' . "\r\n" . '            g.minprice = (select min(marketprice) from ' . tablename('jy_weishop_goods_option') . ' where goodsid = ' . $goodsid . ' and marketprice > 0),' . "\r\n" . '            g.maxprice = (select max(marketprice) from ' . tablename('jy_weishop_goods_option') . ' where goodsid = ' . $goodsid . ')' . "\r\n" . '            where g.id = ' . $goodsid . ' and g.hasoption=1';
		}
		else 
		{
			$sql = 'update ' . tablename('jy_weishop_goods') . ' set minprice = marketprice,maxprice = marketprice where id = ' . $goodsid . ' and hasoption=0;';
		}
		pdo_query($sql);
		*/
		return array('result' => '1', 'goodsid' => $goodsid);
}
function save_image($url, $iscontent) 
	{
		$ext = strrchr($url, '.');
		if (($ext != '.jpeg') && ($ext != '.gif') && ($ext != '.jpg') && ($ext != '.png')) 
		{
			return $url;
		}
		if (trim($url) == '') 
		{
			return $url;
		}
		$filename = random(32) . $ext;
		$save_dir = ROOT_D . '/images/' . $_SESSION['uniacid'] . '/' . date('Y') . '/' . date('m') . '/';
		if (!(file_exists($save_dir)) && !(mkdir($save_dir, 511, true))) 
		{
			return $url;
		}
		$img = ihttp_get($url);
		if (is_error($img)) 
		{
			return '';
		}
		$img = $img['content'];
		if (strlen($img) != 0) 
		{
			file_put_contents($save_dir . $filename, $img);
			$imgdir = 'images/' . $_W['uniacid'] . '/' . date('Y') . '/' . date('m') . '/';
			$saveurl = save_media($imgdir . $filename, true);
			return $saveurl;
		}
		return '';
	}
?>